package com.duowan.realtime.scheduled.util;

import com.duowan.datawarehouse.utils.DateUtil;
import org.apache.commons.lang.ArrayUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @author zhanglong
 * @Description: 获取时间片时间的工具类
 * @date 2013-1-8 上午11:32:27
 */
public class MinuteSlotUtil {

    /**
     * @Description: 传递一个时间片和一个时间参数, 返回此时间所属的时间片时间
     * 合法的slot: 1,5,10,15,20,30,60
     * 以slot=5为例:
     * slot=5,表示要获取time参数所属的5分钟片段时间
     * slot=5,time="2013-01-08 13:24:34" 则返回时间为"2013-01-08 13:20:00"
     */
    public static Date getSlotTime(int slot, Date time) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(time);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        int slots[] = new int[]{1, 5, 10, 15, 20, 30, 60};
        if (ArrayUtils.contains(slots, slot)) {
            int minuteSlot = (calendar.get(Calendar.MINUTE) / slot) * slot;
            calendar.set(Calendar.MINUTE, minuteSlot);
            return calendar.getTime();
        } else {
            throw new RuntimeException("时间片参数不合法,不支持此参数");
        }
    }

    public static Date getSlotTime(int slot, String time, String pattern) throws ParseException {
        return getSlotTime(slot, new SimpleDateFormat(pattern).parse(time));
    }


    public static String getSlotTimeStr(int slot, Date time, String pattern) {
        return DateUtil.formatDate(getSlotTime(slot, time), pattern);
    }

    public static String getSlotTimeStr(int slot, String time, String pattern) throws ParseException {
        return getSlotTimeStr(slot, new SimpleDateFormat(pattern).parse(time), pattern);
    }

    public static void main(String[] args) {
        String mtime = getSlotTimeStr(5, new Date(), "yyyy-MM-dd HH:mm");
        String htime = getSlotTimeStr(5, new Date(), "yyyy-MM-dd HH");
        System.out.println(mtime);
        System.out.println(htime);
    }


}
